﻿namespace TwiMixer.Handlers
{
    using System;
    using System.Text.RegularExpressions;
    using System.Web;
    using TwiMixer.RESTAPI;
    using Twitterizer;

    /// <summary>
    /// callbackhandler 保存用户的accesstoken
    /// </summary>
    public class OAuthCallbackHandler : IHttpHandler
    {
        /// <summary>
        /// handler重用
        /// </summary>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// 保存用户access token
        /// </summary>
        /// <param name="context">httpcontext</param>
        public void ProcessRequest(HttpContext context)
        {
            APIProviderEnum api = (APIProviderEnum)Enum.Parse(typeof(APIProviderEnum), context.Request.Params["api"]);
            APIProvider provider = (APIProvider)APIProviderFactory.GetApiProvider(api);

            string requestToken = context.Request.Params["oauth_token"];
            string verifier = context.Request.Params["oauth_verifier"];
            string requesetTokenSecret = context.Request.Cookies[requestToken].Value;

            OAuthTokenResponse response = provider.GetOAuthToken(requestToken, verifier, requesetTokenSecret);

            // 渣浪不会返回screen_name 手动从users/show.json获取
            OAuthTokens token;
            switch (api)
            {
                case APIProviderEnum.twimixer:
                    break;
                case APIProviderEnum.tweet:
                    break;
                case APIProviderEnum.sina:
                    token = Utility.TokenResponse2Token(response);
                    string responseBody = provider.GetRESTUsersShow(token, response.UserId.ToString());
                    response.ScreenName = Regex.Match(responseBody, "\"screen_name\":\"(\\w+)\"").Groups[1].Value;
                    break;
                case APIProviderEnum.tencent:
                    break;
                default:
                    break;
            }

            // 保存token的用户基本信息到文件
            string uId = Utility.SaveUserToken(response, provider.ApiProviderType.ToString());

            // context.Response.Write("http://"
        }
    }
}